package com.jb.repair.net;

import android.content.Context;
import android.util.Log;

import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.model.FileLbModel;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLHandshakeException;

/***
 * Http通信中的POST和GET请求方式的不同。GET把参数放在URL字符串后面，传递给服务器。
 * 而POST方法的参数是放在Http请求中，主要用于手机对Http访问提供公共的访问类对象。
 *
 * @author hlj
 * @date
 * @versionn 1.0
 **/
public class HttpClient {

    /**
     * 设置网络请求超时时间，某些情况下特殊请求的时间较长
     *
     * @param socketTimeOut 单位为秒
     */
    public void setSocketTimeOut(int socketTimeOut) {
        HttpConnectionParams.setSoTimeout(httpClient.getParams(),
                socketTimeOut * 1000);
    }

    /**
     * 将网络请求超时时间重置为默认值
     */
    public void resetSocketTimeOut() {
        HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5 * 1000);
    }

    /**
     * 执行downfile后，得到下载文件的大小
     */
    private long contentLength;
    /**
     * 返回连接失败信息
     **/
    private String strResult = "服务器无法连接，请检查网络";

    /**
     * http 请求头参数
     **/
    private HttpParams httpParams;
    /**
     * httpClient 对象
     **/
    private DefaultHttpClient httpClient;
    /**
     * 得到上下文
     **/
    private Context context;

    public HttpClient(Context act) {
        this.context = act;
        getHttpClient();
    }

    /**
     * 提供GET形式的访问网络请求 doGet 参数示例： Map params=new HashMap();
     * params.put("usename","helijun"); params.put("password","123456");
     * httpClient.doGet(url,params)；
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回 String jsonResult;
     **/
    @SuppressWarnings("unchecked")
    public String doGet(String url, Map params) {
        /** 建立HTTPGet对象 **/
        String paramStr = "";
        if (params == null)
            params = new HashMap();
        /** 迭代请求参数集合 **/
        Iterator iter = params.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            String val = nullToString(entry.getValue());
            paramStr += paramStr = "&" + key + "=" + URLEncoder.encode(val);
        }
        if (!paramStr.equals("")) {
            paramStr = paramStr.replaceFirst("&", "?");
            url += paramStr;
        }
        return doGet(url);
    }

    /**
     * 提供GET形式的访问网络请求 doGet 参数示例： Map params=new HashMap();
     * params.put("usename","gongshuanglin"); params.put("password","123456");
     * httpClient.doGet(url,params)；
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回 String jsonResult;
     */
    public String doGet(String url, List<NameValuePair> params) {
        /** 建立HTTPGet对象 **/
        String paramStr = "";
        if (params == null)
            params = new ArrayList<NameValuePair>();
        /** 迭代请求参数集合 **/

        for (NameValuePair obj : params) {
            paramStr += paramStr = "&" + obj.getName() + "="
                    + URLEncoder.encode(obj.getValue());
        }
        if (!paramStr.equals("")) {
            paramStr = paramStr.replaceFirst("&", "?");
            url += paramStr;
        }
        return doGet(url);
    }

    /**
     * 提供GET形式的访问网络请求 doGet 参数示例：
     *
     * @param url 请求地址
     * @return 返回 String jsonResult;
     */
    public String doGet(String url) {
        // 是否要重试
        boolean retry = true;
        int retryCount = 0;
        // 最大的重试次数
        int maxRetryCount = 3;
        do {
            /** 创建HttpGet对象 **/
            HttpGet httpRequest = new HttpGet(url);
            httpRequest.setHeaders(this.getHeader());
            httpRequest.setHeader("Accept-Encoding", "gzip");// 设置压缩格式
            try {
                /** 保持会话Session **/
                /** 设置Cookie **/
                HttpCookies li = new HttpCookies(context);
                CookieStore cs = li.getuCookie();
                /** 第一次请求App保存的Cookie为空，所以什么也不做，只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/
                if (cs != null) {
                    httpClient.setCookieStore(li.getuCookie());
                }

                /** 保持会话Session end **/

				/* 发送请求并等待响应 */
                HttpResponse httpResponse = httpClient.execute(httpRequest);
                int resCode = httpResponse.getStatusLine().getStatusCode();
                /* 若状态码为200 ok */

                if (resCode == 200) {
                    retry = false;
                    /* 读返回数据 */
                    strResult = EntityUtils
                            .toString(new GzipDecompressingEntity(httpResponse
                                    .getEntity()));

                    /** 执行成功之后得到 **/
                    /** 成功之后把返回成功的Cookis保存APP中 **/
                    // 请求成功之后，每次都设置Cookis。保证每次请求都是最新的Cookis
                    li.setuCookie(httpClient.getCookieStore());

                } else if (resCode == 404) {
                    strResult = "Error Response: "
                            + httpResponse.getStatusLine().toString();
                } else {
                    strResult = "Error Response: "
                            + httpResponse.getStatusLine().toString();
                }
            } catch (ClientProtocolException e) {
                strResult = nullToString(e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                strResult = nullToString(e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                strResult = nullToString(e.getMessage());
                e.printStackTrace();
            } finally {

                httpRequest.abort();
            }
            retryCount++;
        } while (retry && retryCount < maxRetryCount);
        this.shutDownClient();
        return strResult;
    }

    /**
     * 提供Post形式的访问网络请求 Post 参数示例： doPost 参数示例 List<NameValuePair> paramlist =
     * new ArrayList<NameValuePair>(); paramlist(new BasicNameValuePair("email",
     * "xxx@123.com")); paramlist(new BasicNameValuePair("address", "123abc"));
     * httpClient.doPost(url,paramlist);
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回 String jsonResult;
     **/

    public String doPost(String url, Map<String, String> params) {
        return doPost(url, getNameValuePair(params));
    }

    /**
     * 提供Post形式的访问网络请求 Post 参数示例： doPost 参数示例 List<NameValuePair> paramlist =
     * new ArrayList<NameValuePair>(); paramlist(new BasicNameValuePair("email",
     * "xxx@123.com")); paramlist(new BasicNameValuePair("address", "123abc"));
     * httpClient.doPost(url,paramlist);
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回 String jsonResult;
     **/

    public synchronized String doPost(String url, List<NameValuePair> params) {
//        boolean retryAble = true;
//        int count = 0;
//        do {
//            count++;
//            if (count >= 3) {
//                retryAble = false;
//            }
            /* 建立HTTPPost对象 */
            HttpPost httpRequest = new HttpPost(url);
            // 设置请求Header信息、
            httpRequest.setHeaders(this.getHeader());
            httpRequest.setHeader("Accept-Encoding", "gzip");// 设置压缩格式

            try {

                /** 添加请求参数到请求对象 */
                httpRequest.setEntity(new UrlEncodedFormEntity(params,
                        HTTP.UTF_8));

                /** 保持会话Session **/
                /** 设置Cookie **/
                HttpCookies li = new HttpCookies(context);
                CookieStore cs = li.getuCookie();
                /**
                 * 第一次请求App保存的Cookie为空，所以什么也不做，只有当APP的Cookie不为空的时。把请请求的Cookie放进去
                 **/
                if (cs != null) {
                    httpClient.setCookieStore(li.getuCookie());
                }
                // 关闭100-continue
                httpRequest.getParams().setBooleanParameter(
                        CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
                /** 保持会话Session end **/

                /** 发送请求并等待响应 */

                HttpResponse httpResponse = httpClient.execute(httpRequest);

//                retryAble = false;
                int resCode = httpResponse.getStatusLine().getStatusCode();
                /** 若状态码为200 ok */
                if (resCode == 200) {
                    /* 读返回数据 */
                    HttpEntity entity = httpResponse.getEntity();
                    strResult = EntityUtils
                            .toString(new GzipDecompressingEntity(httpResponse
                                    .getEntity()));
                    /** 执行成功之后得到 **/
                    /** 成功之后把返回成功的Cookis保存APP中 **/
                    // 请求成功之后，每次都设置Cookis。保证每次请求都是最新的Cookis
                    li.setuCookie(httpClient.getCookieStore());

                    /** 设置Cookie end **/
                } else if (resCode == 404) {
                    strResult = resCode + "请求失败，请检查服务器地址是否正确";
                } else {
                    strResult = resCode + "请求失败，请检查服务器地址是否正确";
                }
            } catch (ClientProtocolException e) {
                strResult = "请求失败，请联系管理员！";
                e.printStackTrace();
            } catch (IOException e) {
                strResult = "请求失败，请稍后重试！";
                e.printStackTrace();
            } catch (Exception e) {
                strResult = "服务器连接失败!";
                e.printStackTrace();
            } finally {
                httpRequest.abort();

            }
//
//        } while (retryAble);
        return strResult;
    }

    /**
     * 得到 apache http HttpClient对象
     **/
    public DefaultHttpClient getHttpClient() {

        /** 创建 HttpParams 以用来设置 HTTP 参数 **/

        httpParams = new BasicHttpParams();

        /** 设置连接超时和 Socket 超时，以及 Socket 缓存大小 **/

        HttpConnectionParams.setConnectionTimeout(httpParams, 600 * 1000);

        HttpConnectionParams.setSoTimeout(httpParams, 600 * 1000);

        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

        HttpClientParams.setRedirecting(httpParams, true);

        /**
         * 创建一个 HttpClient 实例 //增加自动选择网络，自适应cmwap、CMNET、wifi或3G
         */
        HttpCookies li = new HttpCookies(context);
        String proxyStr = li.getHttpProxyStr();
        if (proxyStr != null && proxyStr.trim().length() > 0) {
            HttpHost proxy = new HttpHost(proxyStr, 80);
            // httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
            // proxy);
        }
        /** 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient **/

        httpClient = new DefaultHttpClient(httpParams);
        httpClient.setHttpRequestRetryHandler(requestRetryHandler);

        return httpClient;

    }

    /**
     * 得到设备信息、系统版本、驱动类型
     **/
    private Header[] getHeader() {
        /** 请求头信息 end **/
        HttpCookies li = new HttpCookies(context);
        return li.getHttpHeader();
    }

    /**
     * 销毁HTTPCLient
     **/
    public void shutDownClient() {
        httpClient.getConnectionManager().shutdown();
    }

    /**
     * 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
     */
    private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
        // 自定义的恢复策略
        public boolean retryRequest(IOException exception, int executionCount,
                                    HttpContext context) {
            // 设置恢复策略，在发生异常时候将自动重试N次
            if (executionCount >= 3) {
                // 如果超过最大重试次数，那么就不要继续了
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                // 如果服务器丢掉了连接，那么就重试
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                // 不要重试SSL握手异常
                return false;
            }
            HttpRequest request = (HttpRequest) context
                    .getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
            if (!idempotent) {
                // 如果请求被认为是幂等的，那么就重试
                return true;
            }
            return false;
        }
    };

    public long getContentLength() {
        return contentLength;
    }

    /**
     * 假如obj对象 是null返回""
     *
     * @param obj
     * @return
     */
    public static String nullToString(Object obj) {
        if (obj == null) {
            return "";
        }
        return obj.toString();
    }

    private List<NameValuePair> getNameValuePair(final Map<String, String> maps) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Iterator iterator = maps.keySet().iterator(); iterator.hasNext(); ) {
            String key = (String) iterator.next();
            pairs.add(getNameValuePair(key, maps.get(key)));
        }
        return pairs;
    }

    private NameValuePair getNameValuePair(final String key, final String value) {
        NameValuePair pair = new NameValuePair() {

            @Override
            public String getValue() {
                return value;
            }

            @Override
            public String getName() {
                return key;
            }
        };
        return pair;
    }

    /**
     * 客户端上传文件到服务器
     */
    public Boolean upLoadFile(FileLbModel model) {
        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httpPost = new HttpPost(AppConfig.BASE_URL + Constants.UPLOAD_FILE_URL);
        Log.i("MainActivity", "上传文件url：" + AppConfig.BASE_URL + Constants.UPLOAD_FILE_URL);

        MultipartEntity postEntity = new MultipartEntity();

        try {
            // 文件用FileBody
            File filef = new File(AppConfig.UPLOAD_PATH + model.guid + ".xlsx");
            ContentBody file = new FileBody(filef);


            // 把上面创建的这些Body全部加到Entity里面去。
            // 注意他们的key，这些key在Struts2服务器端Action的代码里必须保持一致！！
            postEntity.addPart("tablename", new StringBody(model.table));
            postEntity.addPart("file", file);
            postEntity.addPart("zlxxmc", new StringBody(model.clounm));
            postEntity.addPart("belong_id", new StringBody(model.lineId));
            postEntity.addPart("file_guid", new StringBody(model.guid));
            postEntity.addPart("file_name", new StringBody(model.wjmc));
            postEntity.addPart("lx", new StringBody("jpg"));
            httpPost.setEntity(postEntity);

            HttpCookies li = new HttpCookies(context);
            CookieStore cs = li.getuCookie();
            /**
             * 第一次请求App保存的Cookie为空，所以什么也不做，只有当APP的Cookie不为空的时。把请请求的Cookie放进去
             **/
            if (cs != null) {
                httpClient.setCookieStore(li.getuCookie());
            }

            HttpResponse response = httpClient.execute(httpPost);

            // 打开response的数据流，就可以读取服务器端的回执数据
            InputStream in = response.getEntity().getContent();

            int count = 0;
            while (count == 0) {
                count = Integer.parseInt(""

                        + response.getEntity().getContentLength());//in.available();
            }
            byte[] bytes = new byte[count];
            int readCount = 0; // 已经成功读取的字节的个数
            while (readCount <= count) {
                if (readCount == count)
                    break;
                readCount += in.read(bytes, readCount, count - readCount);
            }

            //转换成字符串
            String readContent = new String(bytes, 0, readCount);
            Log.i("MainActivity", "上传文件反复结果：" + readContent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 上传任务表
     *
     * @param url      上传接口地址
     * @param path     待上传文件路径
     * @param fileName 待上传文件名称
     * @return
     */
    public String uploadTaskTable(String url, String path, String fileName) {
        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httpPost = new HttpPost(AppConfig.BASE_URL + Constants.UPLOAD_TASK_TABLE_URL);
        MultipartEntity postEntity = new MultipartEntity();
        try {
            // 文件用FileBody
            File filef = new File(path);
            ContentBody file = new FileBody(filef);

            // 把上面创建的这些Body全部加到Entity里面去。
            // 注意他们的key，这些key在Struts2服务器端Action的代码里必须保持一致！！
            postEntity.addPart("tableName", new StringBody("US_APP.TB_CT_TASK_DETAIL"));
            postEntity.addPart("zlxxmc", new StringBody("FJID"));
            postEntity.addPart("zbGuid", new StringBody(""));
            postEntity.addPart("fileName", new StringBody(URLEncoder.encode(fileName, "utf-8")));
            postEntity.addPart("file", file);
            httpPost.setEntity(postEntity);

            HttpCookies li = new HttpCookies(context);
            CookieStore cs = li.getuCookie();
            /**
             * 第一次请求App保存的Cookie为空，所以什么也不做，只有当APP的Cookie不为空的时。把请求的Cookie放进去
             **/
            if (cs != null) {
                httpClient.setCookieStore(li.getuCookie());
            }

            HttpResponse response = httpClient.execute(httpPost);

            // 打开response的数据流，就可以读取服务器端的回执数据
            InputStream in = response.getEntity().getContent();

            int length = 0;
            int count = 0;
            while (length == 0 && count <= 3) {
                count++;
                length = Integer.parseInt("" + response.getEntity().getContentLength());//in.available();
            }
            Log.i("TaskDetailActivity", "length = " + length);
            if (length > 0) {
                byte[] bytes = new byte[length];
                int readCount = 0; // 已经成功读取的字节的个数
                while (readCount <= length) {
                    if (readCount == length)
                        break;
                    readCount += in.read(bytes, readCount, length - readCount);
                }

                //转换成字符串
                String readContent = new String(bytes, 0, readCount);
                Log.i("TaskDetailActivity", "上传任务表结果：" + readContent);
                return readContent;
            } else if (length == -1) {
                //未登录授权
                return "-2";
            } else if (length == 0) {
                //todo 未知原因，先用假逻辑
                return "-3";
            } else
                return "-1";

        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }

    }

    public Boolean downFile(Context context, String url, String fileName) {
        HttpPost httpRequest = new HttpPost(url);
        httpRequest.setHeaders(this.getHeader());
        httpRequest.setHeader("Accept-Encoding", "gzip");// 设置压缩格式
        try {
            HttpCookies li = new HttpCookies(context);
            CookieStore cs = li.getuCookie();
            if (cs != null) {
                httpClient.setCookieStore(li.getuCookie());
            }
            httpRequest.getParams().setBooleanParameter(
                    CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            /** 保持会话Session end **/

            /** 发送请求并等待响应 */
            HttpResponse httpResponse = httpClient.execute(httpRequest);
            int resCode = httpResponse.getStatusLine().getStatusCode();
            /** 若状态码为200 ok */
            if (resCode == 200) {
                HttpEntity entity = httpResponse.getEntity();
                try {
                    InputStream in = entity.getContent();
                    String path = AppConfig.ATTACHMENT_PATh;
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    int length = 0;
                    FileOutputStream out = new FileOutputStream(new File(path + "gaobin.html"));
                    byte[] buff = new byte[1024 * 1024];
                    while ((length = in.read(buff)) > 0) {
                        out.write(buff, 0, length);
                    }
                    in.close();
                    out.flush();
                    out.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                li.setuCookie(httpClient.getCookieStore());
            } else if (resCode == 404) {
            } else {
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpRequest.abort();
        }
        return false;
    }

}